package com.yh.service.impl;

import com.yh.Shopping;
import com.yh.cache.GoodsCache;
import com.yh.cache.ShoppingCache;
import com.yh.pojo.Fruits;
import com.yh.service.ShoppingService;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

public class ShoppingServiceImpl implements ShoppingService {

    @Override
    public BigDecimal allPrice() {

        //总额
        BigDecimal allPrice = BigDecimal.ZERO;

        //购物车是否为空
        if (ShoppingCache.shoppingCache.isEmpty()){
            return allPrice;
        }

        //遍历购物车
        for (Map.Entry<Long, Integer> fruitsAndNums : ShoppingCache.shoppingCache.entrySet()) {
            Fruits fruits = GoodsCache.getFruits(fruitsAndNums.getKey());

            BigDecimal price = new BigDecimal(fruits.getPrice().toString());
            BigDecimal a = price.multiply(new BigDecimal(fruitsAndNums.getValue()));
            //计算价格
            allPrice = allPrice.add(a);
        }

        return allPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
    }

    @Override
    public BigDecimal allPriceByAllowance(String allowance) throws Exception{

        BigDecimal allowanceBigDecimal = null;
        try {
            allowanceBigDecimal = new BigDecimal(allowance);
        } catch (NumberFormatException e) {
            System.out.println("折扣异常");
            return BigDecimal.ZERO;
        }

        //是否大于0 小于1
        if (allowanceBigDecimal.compareTo(BigDecimal.ZERO) < 0 || allowanceBigDecimal.compareTo(BigDecimal.ONE) > 0) {
            System.out.println("折扣异常！！");
            return BigDecimal.ZERO;
        }

        //总额
        BigDecimal allPrice = allPrice();

        //计算折扣
        allPrice = allPrice.multiply(allowanceBigDecimal);

        return allPrice.setScale(2,BigDecimal.ROUND_HALF_UP);

    }

    @Override
    public BigDecimal allPriceByFullDecrement(BigDecimal fullMoney, BigDecimal decrementMoney) {

        //计算购物车总额
        BigDecimal allPrice = allPrice();

        //是否符合满减条件
        if (allPrice.compareTo(fullMoney) < 0) {
            return allPrice;
        }

        //计算满减
        allPrice = allPrice.subtract(decrementMoney);

        return allPrice.setScale(2,BigDecimal.ROUND_HALF_UP);
    }
}
